<?php
class Backend_Orm_Controller extends Backend_Controller
{
    public function __construct()
    {
    	parent::__construct();
    	$cfg = Application::getConfig();
    	Db_Object_Builder::writeLog($cfg['use_orm_build_log']);
        Db_Object_Builder::setLogPrefix($cfg['development_version'].'_build_log.sql');
        Db_Object_Builder::setLogsPath($cfg['orm_log_path']);
    }
    
    public function indexAction(){
        $res = Resource::getInstance();   
        $this->_resource->addInlineJs('
            var canPublish =  '.((integer)$this->_user->canPublish($this->_module)).';
        	var canEdit = '.((integer)$this->_user->canEdit($this->_module)).';
        	var canDelete = '.((integer)$this->_user->canDelete($this->_module)).';
        	var canUserBackup = '.((integer)($this->_hasZipModule() && $this->_isLocalhost())).';
        ');
        $res->addJs('/js/app/system/SearchPanel.js'  , 0);   
	    $res->addJs('/js/app/system/crud/orm.js'  , 1);
	    $res->addJs('/js/app/system/crud/orm/objectWindow.js'  , 2);
        $res->addJs('/js/app/system/crud/orm/fieldWindow.js'  , 2);
        $res->addJs('/js/app/system/crud/orm/indexWindow.js'  , 2);
        $res->addJs('/js/app/system/crud/orm/restoreBackupWindow.js'  , 2);
        $res->addJs('/js/app/system/crud/orm/dictionaryWindow.js'  , 2);
    }
    
    public function listAction(){
        $data = array(); 
        $cfgPath = $this->_store->get('config_main')->get('object_configs');        
        
        /*
         * Getting list of objects
         */
       // $configs = File::scanFiles($cfgPath , array('.php'), false, File::Files_Only);
        $names = Db_Object_Manager::getRegisteredObjects();
        if(empty($names))
             Response::jsonSuccess(array());

        /*
         * Getting db tables info
         */
        $tablesData = $this->_db->fetchAll("SHOW TABLE STATUS");
        $tables = array();
        if(!empty($tablesData))
            foreach ($tablesData as $k=>$v)
                $tables[$v['Name']] = array(
                	'rows'=>$v['Rows'],
                	'data_length'=>$v['Data_length'],
                	'index_length'=>$v['Index_length']
                );
                
        unset($tablesData);
        
        /*
         * forming result set
         */
        $prefix = $this->_store->get('dbConfig')->get('prefix'); 
        foreach ($names as $objectName){
     	
        	 $configObject = Db_Object_Config::getInstance($objectName);
        	 $config =  $configObject->__toArray();
        	 $objectTable = $configObject->getTable();
                       
             $records = 0;
             $dataLength = 0;
             $indexLength=0;
             
             if(isset($tables[$objectTable])){
                 $records = $tables[$objectTable]['rows'];
                 $dataLength = Utils::formatFileSize($tables[$objectTable]['data_length']);
                 $indexLength = Utils::formatFileSize($tables[$objectTable]['index_length']);
             }
                 
             $title=  '';
             $saveHistory = true;
             $linktitle='';

             if(isset($config['title']) && !empty($config['title']))
                 $title = $config['title'];
                 
             if(isset($config['link_title']) && !empty($config['link_title']))
                 $linktitle = $config['link_title'];    
                 
             if(isset($config['save_history']) && !$config['save_history'])  
                  $saveHistory = false;
                 
             $data[] = array(
                        'name'=> $objectName,
			 	        'table'=> $objectTable,
             			'title'=>$config['title'],
			 	        'engine'=>$config['engine'],	 	        
			 	        'vc'=>$config['rev_control'],
			 	        'fields'=>sizeof($config['fields']),
			 	        'records'=>$records,
                        'title'=>$title,
                        'link_title'=>$linktitle,
                        'rev_control'=>$config['rev_control'],
             			'save_history'=>$saveHistory,
             			'data_size'=>$dataLength,
             			'index_size'=>$indexLength,
             			'validdb'=>Db_Object_Builder::getInstance()->validate(new Db_Object($objectName))
             );
             
         }
         Response::jsonSuccess($data);
    }
    /**
     * Create backups (DB data and object configs)
     * @return void
     */
    public function makebackupAction() {    		
    	ini_set('ignore_user_abort', 'On');
    	ini_set('max_execution_time',3600);
    	$name = date('d-m-Y_H:i:s');
    	$dumpdir = $this->_configMain->get('backups');
    	$objectConfigsPath = $this->_configMain->get('object_configs');
    	$objectsPath = $this->_configMain->get('configs');
    	$sqlPath = $dumpdir . '/sql/dump.sql';
    	    	
    	$files = File::scanFiles($objectConfigsPath, array('.php'), true, File::Files_Only);
    	
    	File::zipFiles($name, $dumpdir, $files, $objectsPath);
    	
    	if(!mkdir($dumpdir . 'sql', 0775))
    		Response::jsonError($this->_lang->CANT_WRITE_FS);
    		
        $dbConfig = $this->_store->get('dbConfig');
        
    	$cmd = $this->_configMain->get('mysqldumpExecutable').' -u' . $dbConfig->get('username') 
    			. ' -p' . $dbConfig->get('password') . ' --add-drop-table -R -K ' . $dbConfig->get('dbname') 
    			. ' > ' . $sqlPath;
    			
    	system($cmd);
    	
    	File::zipFiles($name, $dumpdir, $sqlPath, $dumpdir);
    	
    	@unlink($sqlPath);
    	@rmdir($dumpdir . 'sql');
    	
    	Response::jsonSuccess();				
    }
    /**
     * Get a list of existing backups
     * @return void
     */
    public function listbackupsAction(){
    	$backups = File::scanFiles($this->_configMain->get('backups'), array('.zip'), false, File::Files_Only);
    	
    	$res = array();
    	foreach ($backups as $v)
    		$res[]['title'] = str_replace('/', '', strrchr($v, '/'));
    	
    	Response::jsonArray($res);
    }
    /**
     * Restore backups (DB data and object configs)
     * @throws Exception
     * @return void
     */
    public function restorebackupAction() {

    	$name = Request::post('name', 'str', '');
    	$restoreDb = Request::post('sql', 'bool', false);
    	
    	if (!$name)
    		Response::jsonError();
    	
    	ini_set('ignore_user_abort', 'On');
    	ini_set('max_execution_time',3600);
    	$tmpdir = $this->_configMain->get('tmp') . 'backups_restore/';
    	if(!is_dir($tmpdir))
    		mkdir($tmpdir, 0775);
    	
    	File::unzipFiles($this->_configMain->get('backups').$name, $tmpdir);
    	
    	$confObjDir = $this->_configMain->get('object_configs');
    	$objDir = $tmpdir . str_replace($this->_configMain->get('configs'), '', $confObjDir);
    	if (!is_dir($objDir))
    		Response::jsonError('a backup archive does not content an object folder');
    		
    	if ($restoreDb)
    		$this->_restoreDb($tmpdir . 'sql/', 'dump.sql');
    	
    	$objects = File::scanFiles($objDir);
    	
    	if (!empty($objects))
    		foreach ($objects as $v) {
    			$curentName = $confObjDir . str_replace($objDir, '', $v);
    			if (is_dir($v)) {
					if (!is_dir($curentName))
    					mkdir($curentName, 0775);
    			} else {
					copy($v, $curentName);
    			}
    		}
    		
    	$cache = Config::getCacheCore();
    	if ($cache)
    		$cache->clean(
			    Zend_Cache::CLEANING_MODE_MATCHING_TAG,
			    array('config' , 'config_file')
			);
    		
    	File::rmdirRecursive($tmpdir);
    	
    	Response::jsonSuccess();
    }
    public function removebackupAction(){
    	$backup = $this->_configMain->get('backups') . Request::post('name', 'str', '');
    	/**
    	 * Note: Because PHP's integer type is signed and many platforms use 32bit integers, 
    	 * some filesystem functions may return unexpected results for files 
    	 * which are larger than 2GB.
    	 */
    	if(!is_file($backup))
    		Response::jsonError('A backup file is not exists');
    	if(unlink($backup)) 
    		Response::jsonSuccess();
    	else
    		Response::jsonSuccess('Error during execution');
    }
    /**
     * restore Db
     * @param string $sqlDir
     * @param string $fileName
     * @throws Exception
     * @return void
     */
    protected function _restoreDb($sqlDir, $fileName) {
    	if (!is_dir($sqlDir))
    		Response::jsonError('a backup archive does not content an sql folder');
    		
    	$dbConfig = $this->_store->get('dbConfig');
    	
    	$cmd = 'mysql -u' . $dbConfig->get('username') . ' -p' . $dbConfig->get('password') 
    			. ' -t ' . $dbConfig->get('dbname') . ' < ' . $sqlDir . $fileName;
    			
    	system($cmd);
    }
      
    public function fieldsAction(){
    	$object = Request::post('object', 'string', false);
    	
    	if(!$object)
    		Response::jsonError($this->_lang->INVALID_VALUE);
    		
    	try{	
    		$objectConfig = Db_Object_Config::getInstance($object);
    	}catch (Exception $e){
    		Response::jsonError($this->_lang->INVALID_VALUE);
    	}
    	
    	$fieldscfg = $objectConfig->getFieldsConfig();
    	
    	foreach ($fieldscfg as $k=>&$v){
  
    		$v['name'] = $k; 
    		   
    	    if(isset($v['type']) && !empty($v['type'])){
    	        if($v['type'] == 'link'){
    	            $v['type'].= ' ('.$v['link_config']['object'].')';
    	            $v['link_type'] = $v['link_config']['link_type'];
		        	$v['object'] = $v['link_config']['object'];
		        	unset($v['link_config']);
    	        }
    	        continue;
    	    }

    	    $v['unique'] = !empty($v['unique']);
	        $v['type'] =  $v['db_type'];
	        
	        if(in_array($v['db_type'], Db_Object_Builder::$charTypes , true)){
	            $v['type'].=' ('.$v['db_len'].')';        
	        }elseif (in_array($v['db_type'], Db_Object_Builder::$floatTypes , true)){
	            $v['type'].=' ('.$v['db_scale'].','.$v['db_precision'].')';
	        }
    	}unset($v);
    	Response::jsonArray(array_values($fieldscfg));
    }
    
    
    public function indexesAction(){
        $object = Request::post('object', 'string', false);
    	
    	if(!$object)
    		Response::jsonError($this->_lang->INVALID_VALUE);
    		
    	try{	
    		$objectConfig = Db_Object_Config::getInstance($object);
    	}catch (Exception $e){
    		Response::jsonError($this->_lang->INVALID_VALUE);
    	}
    	
    	$indexsesCfg = $objectConfig->getIndexesConfig();
    	
    	foreach ($indexsesCfg as $k=>&$v){
    	    $v['columns'] = implode(', ', $v['columns']);
    	    $v['name'] = $k;
    	}unset($v);
    	
    	Response::jsonArray(array_values($indexsesCfg));
    }
    
    /**
     * Load index config action
     */
    public function loadindexAction(){
        $object = Request::post('object', 'string',false);
        $index = Request::post('index', 'string',false);
        
        if(!$object || !$index)
    		Response::jsonError($this->_lang->INVALID_VALUE);
    
    	try {
    	    $cfg = Db_Object_Config::getInstance($object);
    	}catch (Exception $e){
    	    Response::jsonError($this->_lang->INVALID_VALUE);
    	}	
    	
    	$indexes = $cfg->getIndexesConfig();
    	if(!array_key_exists($index, $indexes))
    	    Response::jsonError($this->_lang->INVALID_VALUE);
    	    
    	$data = $indexes[$index];
    	$data['name'] = $index;
    	Response::jsonSuccess($data);    	
    }
    
    public function loadAction(){
    	$object = Request::post('object', 'string',false);
    	if($object === false)
    		Response::jsonError($this->_lang->INVALID_VALUE);

    	try {
    		$config = Db_Object_Config::getInstance($object);
    		$info = $config->__toArray();
    		$info['name'] = $object;
    		unset($info['fields']);
    		Response::jsonSuccess($info);
    	}catch (Exception $e){
    		Response::jsonError($this->_lang->INVALID_VALUE);	
    	}
    }
    
    /**
     * @todo validate index columns, check if they exists in config
     */
    public function saveindexAction()
    {
    	$this->_checkCanEdit();
            
        $object =  Request::post('object', 'string', false);
        $index =   Request::post('index', 'string', false);
        $columns = Request::post('columns', 'array', array());
        $name = Request::post('name', 'string', false);
        $unique = Request::post('unique', 'boolean', false);
        $fulltext =Request::post('fulltext', 'boolean', false);
        
        if(!$object)
            Response::jsonError($this->_lang->WRONG_REQUEST.' code 1');
            
        if(!$name)
            Response::jsonError($this->_lang->FILL_FORM , array(array('id'=>'name','msg'=>$this->_lang->CANT_BE_EMPTY)));

        try{
            $objectCfg = Db_Object_Config::getInstance($object);
        }catch (Exception $e){
            Response::jsonError($this->_lang->WRONG_REQUEST .' code 2');
        }
            
            
        $indexData = array(
             'columns'=>$columns,
             'unique'=>$unique,
             'fulltext'=>$fulltext,
             'PRIMARY'=>false
        );
        
         $indexes = $objectCfg->getIndexesConfig();  
             
         if($index !== $name && array_key_exists((string)$name, $indexes))
               Response::jsonError($this->_lang->FILL_FORM , array(array('id'=>'name','msg'=>$this->_lang->SB_UNIQUE)));  
         
         if($index!=$name)
             $objectCfg->removeIndex($index);

         $objectCfg->setIndexConfig($name, $indexData);
         
         if($objectCfg->save())
             Response::jsonSuccess();
         else     
             Response::jsonError($this->_lang->CANT_WRITE_FS); 
    }
    
    public function deletefieldAction(){
    	$this->_checkCanDelete();
    	
        $object =  Request::post('object', 'string', false);
        $field =   Request::post('name', 'string', false);
        
        if(!$object || !$field)
            Response::jsonError($this->_lang->WRONG_REQUEST);
            
        try{
            $objectCfg = Db_Object_Config::getInstance($object);
        }catch (Exception $e){
            Response::jsonError($this->_lang->WRONG_REQUEST .' code 2');
        }   
        
        $objectCfg->removeField($field);
             
         if($objectCfg->save())
             Response::jsonSuccess();
         else 
             Response::jsonError($this->_lang->CANT_WRITE_FS);
    }
    
    public function deleteindexAction(){
        $this->_checkCanDelete();

        $object =  Request::post('object', 'string', false);
        $index =   Request::post('name', 'string', false);
        
        if(!$object || !$index)
            Response::jsonError($this->_lang->WRONG_REQUEST);
            
        try{
            $objectCfg = Db_Object_Config::getInstance($object);
        }catch (Exception $e){
            Response::jsonError($this->_lang->WRONG_REQUEST .' code 2');
        }   
        
        $objectCfg->removeIndex($index);
        
        if($objectCfg->save())
            Response::jsonSuccess();
        else 
            Response::jsonError($this->_lang->CANT_WRITE_FS);
    }

    /**
     * @todo cleanup the code 
     * Enter description here ...
     */
    public function saveAction()
    {    
    	$this->_checkCanEdit();
            
    	$builder = Db_Object_Builder::getInstance();
    	$recordId = Request::post('record_id', 'string', '0');
    	$revControl = Request::post('rev_control', 'boolean', false);
    	$saveHistory = Request::post('save_history', 'boolean', false);
    	$linkTitle = Request::post('link_title', 'string', '');
    	$name = Request::post('name', 'string', '');
    	
    	$reqStrings = array('name','title','table', 'engine');
    	$errors = array();
    	$data = array();
    	
    	foreach ($reqStrings as $v){
    		$value = Request::post($v, 'string', '');
    		
    		if($v!=='name'){
    			$data[$v] = $value;
    			
    			if(!strlen($data[$v]))
    				$errors[] = array('id'=>$v ,'msg'=>$this->_lang->CANT_BE_EMPTY);
    		}
    	}
    	
    	if(!empty($errors))
    		Response::jsonError($this->_lang->FILL_FORM , $errors);
    	   	
    	$data['rev_control'] = $revControl;
    	$data['save_history'] = $saveHistory;
    	$data['link_title'] = $linkTitle;   		
    		
    	if($recordId === ''){
    	     
    		if($builder->tableExists($data['table']))
    			Response::jsonError($this->_lang->FILL_FORM , array('id'=>'table','msg'=>$this->_lang->SB_UNIQUE));
    			
    		try {
    			$cfg = Config::factory(Config::File_Array, $this->_configMain->get('object_configs').strtolower($name).'.php');
    			Response::jsonError($this->_lang->FILL_FORM , array('id'=>'name','msg'=>$this->_lang->SB_UNIQUE));
    		}catch (Exception $e){
    		   
    		}	
    		
    		if(Config_File_Array::create($this->_configMain->get('object_configs').$name.'.php')===false)
    			Response::jsonError($this->_lang->CANT_WRITE_FS);
    			
    		$cfg = Config::factory(Config::File_Array, $this->_configMain->get('object_configs').strtolower($name).'.php');
    			  			
    		$data['fields'] = array();	
    			
    		$cfg->setData($data);
    		$cfg->save();
    		$builder = Db_Object_Builder::getInstance();
    		
    		try{
    			$builder->build(new Db_Object($name));
    		}catch (Exception $e){
    			Response::jsonError($this->_lang->CANT_EXEC);
    		}
    		
    		Response::jsonSuccess();
    		
    	}else{
    		
    		
    		try {
    			$config = Config::factory(Config::File_Array, $this->_configMain->get('object_configs').$recordId.'.php');		
    		}catch (Exception $e){
    			Response::jsonError($this->_lang->INVALID_VALUE);
    		}
    		
    		if(!is_writable($this->_configMain->get('object_configs').$recordId.'.php'))
    			Response::jsonError($this->_lang->CANT_WRITE_FS .'check');
    		
    		
    			if($config->get('engine')!==$data['engine']){		
    				if(!$builder->changeTableEngine($config->get('table') , $data['engine']))
    					Response::jsonError($this->_lang->CANT_EXEC);
    				
    			}
    		
    			if($config->get('table')!==$data['table']){		
    				if($builder->tableExists($data['table']))
    					Response::jsonError($this->_lang->FILL_FORM , array('id'=>'table','msg'=>$this->_lang->SB_UNIQUE));	
    					
    				$renameDb = true;	

    				if(!$builder->renameTable($config->get('table'), $data['table'])){
    					Response::jsonError($this->_lang->CANT_EXEC);
    				}
    			}

    			$config->setData($data);
    			
    			if(!$config->save())
    				Response::jsonError($this->_lang->CANT_WRITE_FS.'save');

	    		if($recordId!=$name){
	    			$newFileName = $this->_configMain->get('object_configs').$name.'.php';
	    			$oldFileName = $this->_configMain->get('object_configs').$recordId.'.php';
	    			
	    			if(file_exists($newFileName))
	    				Response::jsonError($this->_lang->FILL_FORM ,array('id'=>'name','msg'=>$this->_lang->SB_UNIQUE));
	    			
	    			if(!rename($oldFileName, $newFileName))
	    				Response::jsonError($this->_lang->CANT_WRITE_FS . "rename");
	    		
	    			$cache = Config::getCacheCore();
	                if($cache)
	                     $cache->remove($this->_configMain->get('object_configs').$recordId.'.php');
	    		}
	    		
    			Response::jsonSuccess();
    	}
    }
    /**
     * Validate object action
     */
    public function validateAction()
    {

       $name = Request::post('name', 'string', false);
        
       if(!$name)
           Response::jsonError($this->_lang->WRONG_REQUEST);
      
       try {
           $obj = new Db_Object($name);
       } catch (Exception $e){
           Response::jsonError($this->_lang->WRONG_REQUEST);
       }  
         
        $builder = Db_Object_Builder::getInstance();
        $tableExists = $builder->tableExists($obj->getConfig()->get('table'));
      
        $colUpd = array();
        $indUpd = array();
        
        if($tableExists){
        	$colUpd =  $builder->prepareColumnUpdates($obj);
        	$indUpd =  $builder->prepareIndexUpdates($obj);
        }
        
        if(empty($colUpd) && empty($indUpd) && $tableExists)
             Response::jsonSuccess(array(),array('nothingToDo'=>true));

        $template = new Template();
        $template->disableCache();
        $template->columns = $colUpd;
        $template->indexes = $indUpd;
        $template->tableExists = $tableExists;
        $template->tableName = $obj->getTable();
        $template->lang = Lang::getInstance();
        
        $msg = $template->render(Application::getTemplatesPath() . 'orm_validate_msg.php');

        Response::jsonSuccess(array(),array('text'=>$msg,'nothingToDo'=>false));
    }
    /**
     * Build object action
     */
    public function buildAction()
    {
        $this->_checkCanEdit();
            
        $name = Request::post('name', 'string', false);
        
        if(!$name)
             Response::jsonError($this->_lang->WRONG_REQUEST);   
             
        try{
           $obj = new Db_Object($name);
        }catch(Exception $e){
           Response::jsonError($this->_lang->WRONG_REQUEST);
        }  
        $builder = Db_Object_Builder::getInstance();  
        try{
           $builder->build($obj);
           Response::jsonSuccess();
        }catch(Exception $e){
           Response::jsonError($this->_lang->CANT_EXEC);
        }
    }
    /**
     * Build all objects action
     */
    public function buildallAction()
    {
    	$this->_checkCanEdit();
            
    	$names = Request::post('names', 'array', false);
        
        if(empty($names))
			Response::jsonError($this->_lang->WRONG_REQUEST);   
             
		$builder = Db_Object_Builder::getInstance();  
		
		$flag = false;
		foreach ($names as $name) {
	        try{
	           	$obj = new Db_Object($name);
	           	$builder->build($obj);
	        }catch(Exception $e){
	        	$flag = true;
	        }
		}
		if ($flag)
			Response::jsonError($this->_lang->CANT_EXEC);
		else
           	Response::jsonSuccess();
    }
    
    public function loadfieldAction(){
        $object = Request::post('object', 'string',false);
        $field = Request::post('field', 'string',false);
        
        if(!$object || !$field)
    		Response::jsonError($this->_lang->INVALID_VALUE);
    
    	try {
    	    $cfg = Db_Object_Config::getInstance($object);
    	}catch (Exception $e){
    	    Response::jsonError($this->_lang->INVALID_VALUE);
    	}	
    	
    	if(!$cfg->fieldExists($field))
    	     Response::jsonError($this->_lang->INVALID_VALUE);
    	
    	$fieldCfg = $cfg->getFieldConfig($field);
    	$fieldCfg['name'] = $field;
    	
    	if(!isset($fieldCfg['type']) || empty($fieldCfg['type']))
    	    $fieldCfg['type'] = '';
    	    
    	if(isset($fieldCfg['link_config']) && !empty($fieldCfg['link_config']))
    	    foreach ($fieldCfg['link_config'] as $k=>$v)
    	        $fieldCfg[$k] = $v;   
    		
    	Response::jsonSuccess($fieldCfg);    	
    }
    
    /**
     * Save field configuration options
     */
    public function savefieldAction()
    {
    	$this->_checkCanEdit();
    	
    	$object = Request::post('objectName', 'string', false);
    	$objectField = Request::post('objectField', 'string', false);
    	$name = Request::post('name', 'string', false);
	  	
    	if(!$object)
    		Response::jsonError($this->_lang->WRONG_REQUEST);
    		
    	if(!$name)	
    	 	Response::jsonError($this->_lang->FILL_FORM , array(array('id'=>'name','msg'=>$this->_lang->CANT_BE_EMPTY)));	
    		   	
    	try{
    		/**
    		 * @var Db_Object_Config
    		 */
    		$objectCfg = Db_Object_Config::getInstance($object);
        }catch (Exception $e){
            Response::jsonError($this->_lang->WRONG_REQUEST .' code 2');
        }
    	
        $oFields = array_keys($objectCfg->getFieldsConfig());
    		   		
    	if($objectField !== $name && in_array($name, $oFields , true))
            Response::jsonError($this->_lang->FILL_FORM , array(array('id'=>'name','msg'=>$this->_lang->SB_UNIQUE)));  
             
        $newConfig = array();    
        $newConfig['type'] = Request::post('type', 'str', '');
        $newConfig['title']= Request::post('title', 'str', '');
        $newConfig['unique'] = Request::post('unique', 'str', '');
        $newConfig['db_isNull'] = Request::post('db_isNull', 'boolean', false);
        $newConfig['required'] = Request::post('required', 'boolean', false);
        
        if($newConfig['type']=='link'){
	        /**
	         * Process link field
	         */
        	$newConfig['link_config']['link_type'] = Request::post('link_type', 'str', 'object');
        	
        	if($newConfig['link_config']['link_type'] == 'dictionary'){
        		$newConfig['link_config']['object'] = Request::post('dictionary', 'str', '');
        	} else {
	        	$linkedObject = Request::post('object', 'string', false);
	        	if(!$linkedObject)
	        		Response::jsonError($this->_lang->FILL_FORM , array(array('id'=>'object','msg'=>$this->_lang->CANT_BE_EMPTY)));
	        	
	        	try {
	        		$cf = Db_Object_Config::getInstance($linkedObject);
	        	}catch(Exception $e){
	        		Response::jsonError($this->_lang->FILL_FORM , array(array('id'=>'object','msg'=>$this->_lang->INVALID_VALUE)));
	        	}
	        	$newConfig['link_config']['object'] = $linkedObject;
        	}
        }else{
	        /*
	         * Process std field
	         */	
        	 $newConfig['db_type'] = Request::post('db_type', 'str', 'false');
        	 if(!$newConfig['db_type'])
        	 	 Response::jsonError($this->_lang->FILL_FORM , array(array('id'=>'db_type','msg'=>$this->_lang->CANT_BE_EMPTY)));
       	  
        	 if($newConfig['db_type']=='bool' || $newConfig['db_type']=='boolean'){
        	   /*
        	    * boolean
        	    */	
        	 	$newConfig['required'] = false;
        	 	$newConfig['db_default'] = (integer)Request::post('db_default', 'bool', false);    	 	
        	 }elseif(in_array($newConfig['db_type'] , Db_Object_Builder::$intTypes , true)){    	 
        	   /*
        	    * integer
        	    */		
        	 	$newConfig['db_default'] = Request::post('db_default', 'integer', false);
        	 	$newConfig['db_unsigned'] = Request::post('db_unsigned', 'bool', false);	 
        	 }elseif(in_array($newConfig['db_type'], Db_Object_Builder::$floatTypes)){  
        	 	/*
        	 	 * float
        	 	 */      	 	
        	 	$newConfig['db_default'] = Request::post('db_default', 'float', false);
        	 	$newConfig['db_unsigned'] = Request::post('db_unsigned', 'bool', false);
        	 	$newConfig['db_scale'] = Request::post('db_scale', 'integer', 0);
        	 	$newConfig['db_precision'] = Request::post('db_precision', 'integer', 0);       	 
        	 }elseif(in_array($newConfig['db_type'] , Db_Object_Builder::$charTypes , true)){
        	 	/*
        	 	 * char
        	 	 */
        	 	$newConfig['db_default'] = Request::post('db_default', 'string', false);
        	 	$newConfig['db_len'] = Request::post('db_len', 'integer', 255);
        	 	$newConfig['is_search'] =Request::post('is_search', 'bool', false);
        	 	$newConfig['allow_html'] =Request::post('allow_html', 'bool', false);     	 
        	 }elseif(in_array($newConfig['db_type'] , Db_Object_Builder::$textTypes , true)){
        	 	/*
        	 	 * text
        	 	 */
        	 	$newConfig['db_default'] = Request::post('db_default', 'string', false);
        	 	$newConfig['is_search'] =  Request::post('is_search', 'bool', false);
        	 	$newConfig['allow_html'] =Request::post('allow_html', 'bool', false);     	 
        	 }elseif(in_array($newConfig['db_type'] , Db_Object_Builder::$dateTypes , true)){
        	     /*
        	      * date
        	      */
        	 }
        	 else{
        	 	Response::jsonError($this->_lang->FILL_FORM , array(array('id'=>'db_type','msg'=>$this->_lang->INVALID_VALUE)));
        	 }
        } 

        /**
         * @todo Rename
         */
        if($objectField!=$name && !empty($objectField))
        {       	
        	$objectCfg->setFieldconfig($objectField, $newConfig);
        	if(!$objectCfg->renameField($objectField, $name))
        		Response::jsonError($this->_lang->CANT_EXEC); 

        } else{
        	$objectCfg->setFieldconfig($name, $newConfig);
        }

         if($objectCfg->save())
	         Response::jsonSuccess();
	     else     
	         Response::jsonError($this->_lang->CANT_WRITE_FS); 
               
    }

    protected function _hasZipModule()
    {
		$phpExt = get_loaded_extensions();
		return in_array('zip', $phpExt, true);
    }
    
    protected function _isLocalhost()
    {
    	$dbConfig = $this->_store->get('dbConfig')->get('host');
    	return ($dbConfig == 'localhost' || $dbConfig == '127.0.0.1');
    }
    
    
    public function removeobjectAction()
    {
    	$objectName = Request::post('objectName', 'string', false);
    	
    	if(!$objectName)
    		Response::jsonError($this->_lang->WRONG_REQUEST);
    		
    	$path = Application::getConfig()->get('object_configs') . $objectName . '.php';

    	if(@unlink($path) && Db_Object_Builder::getInstance()->remove($objectName))
	    	Response::jsonSuccess();
	    else
	    	Response::jsonError($this->_lang->CANT_EXEC);
    }
    
    
    public function dictionaryAction()
	{
		$subAction = Request::getInstance()->getPath(3);
		if(strlen($subAction))
			$subAction = ucfirst($subAction);
			
		if($subAction===false || !strlen($subAction) || !method_exists($this,'_dictionary'.$subAction))
			Response::jsonError($this->_lang->WRONG_REQUEST);
			
		 $this->{'_dictionary'.$subAction}();		
	}
    

    protected function _dictionaryUpdate()
    {
    	$this->_checkCanEdit();
    	$id = Request::post('id','string',false);
    	$name = Request::post('name','string',false);
    	
    	if(!$name)
    		Response::jsonError($this->_lang->WRONG_REQUEST);
    	
    	if(!$id){
    		if(!Dictionary_Manager::getInstance()->create($name))
    			Response::jsonError($this->_lang->CANT_WRITE_FS);
    	}else{
    		if(!Dictionary_Manager::getInstance()->rename($id, $name))
				Response::jsonError($this->_lang->CANT_WRITE_FS);
    	}
    		
    	Response::jsonSuccess();
    }
        
    protected function _dictionaryRemove()
    {
    	$this->_checkCanDelete();
    	$name = Request::post('name','string',false);
    	if(empty($name))
    		Response::jsonError($this->_lang->WRONG_REQUEST);
    		
		if(!Dictionary_Manager::getInstance()->remove($name))
			Response::jsonError($this->_lang->CANT_EXEC);
    	else
    		Response::jsonSuccess();
    }
    
    protected function _dictionaryList()
    {
    	$data = array();
    	$list = Dictionary_Manager::getInstance()->getList();
    	
    	if(!empty($list))
    		foreach ($list as $v)
    			$data[] = array('id' => $v,'title' => $v);
    			
    	Response::jsonSuccess($data);
    }
    
    protected function _dictionaryRecords()
    {
    	$name = Request::post('dictionary','string',false);
    	if (empty($name))
    		Response::jsonError($this->_lang->WRONG_REQUEST);

    	$list = Dictionary::getInstance($name)->getData();
    	$data = array();
    	
    	if(!empty($list))
    		foreach ($list as $k=>$v)
    			$data[] = array('id' => $k,'key' => $k,'value' => $v);
    	Response::jsonSuccess($data);
    }
    
    protected function _dictionaryUpdaterecords()
    {
    	$this->_checkCanEdit();
    	$dictionaryName = Request::post('dictionary','string',false);
    	$data = Request::post('data','raw',false);
    	$data = json_decode($data, true);

    	if(empty($data) || !strlen($dictionaryName))
    		Response::jsonError($this->_lang->WRONG_REQUEST);
    	
    	$dictionary = Dictionary::getInstance($dictionaryName);
    	foreach ($data as $v)
    	{
    		if($dictionary->isValidKey($v['key']) && $v['key'] != $v['id'])
    			Response::jsonError($this->_lang->WRONG_REQUEST);
    		
    		if(!empty($v['id']))
    			$dictionary->removeRecord($v['id']);
    		$dictionary->addRecord($v['key'], $v['value']);
    	}
    	if(!$dictionary->saveChanges())
    		Response::jsonError($this->_lang->CANT_EXEC);
    	Response::jsonSuccess();
    }
    
    protected function _dictionaryRemoverecords(){
    	$dictionaryName = Request::post('dictionary','string',false);
    	$name = Request::post('name','string',false);
    	
    	if(!strlen($name) || !strlen($dictionaryName))
    		Response::jsonError($this->_lang->WRONG_REQUEST);
    	
    	$dictionary = Dictionary::getInstance($dictionaryName);
    	$dictionary->removeRecord($name);
    	$dictionary->saveChanges();
    	Response::jsonSuccess();
    }
}